package cn.chencq.search;

import java.util.Arrays;

public class BinarySearch {

	public static void main(String[] args) {
		int[] data = new int[] { 5, 8, 6, 7, 2, 9, 1, 0 };
		Arrays.sort(data);
		System.out.println("数组是: " + Arrays.toString(data));
		System.out.println("6对应的下标是：" + Arrays.binarySearch(data, 6));
		System.out.println(search(data, 6));

	}

	/**
	 * 
	 * @Title: search
	 * @Description: 二分法查找
	 * @param arr
	 * @param key
	 * @return int
	 */
	public static int search(int[] arr, int key) {
		int low = 0;
		int high = arr.length - 1;

		while (low <= high) {
			int mid = (low + high) >>> 1;
			int midVal = arr[mid];

			if (midVal < key)
				low = mid + 1;
			else if (midVal > key)
				high = mid - 1;
			else
				return mid;
		}
		return -1;
	}
}
